package com.liuzhilin.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuzhilin.domain.Message;
import com.liuzhilin.service.MessageService;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/chat")
public class ChatWebSocket{
    // 保存所有连接的会话
    private static final Set<Session> sessions = Collections.synchronizedSet(new CopyOnWriteArraySet<>());
    private static final ObjectMapper objectMapper = new ObjectMapper();
    //  处理客户端连接
    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
        System.out.println("客户端已连接: " + session.getId());
    }
    // 处理客户端消息
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            Map<String, Object> data = objectMapper.readValue(message, Map.class);
            int type = (Integer) data.get("type");

            switch (type) {
                case 1: // 获取好友列表
                    handleGetFriends(data, session);
                    break;
                case 2: // 获取历史消息
                    handleGetHistoricalMessages(data, session);
                    break;
                case 5: // 发送消息
                    handleSendMessage(data);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 处理客户端断开连接
    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
        System.out.println("客户端已断开连接: " + session.getId());
    }
    // 处理获取好友列表
    private void handleGetFriends(Map<String, Object> data, Session session) throws IOException {
        String username = (String) data.get("username");
        List<String> friends = MessageService.getFriends(username);
        Map<String, Object> response = new HashMap<>();
        response.put("type", 1); // 返回请求ID
        response.put("friends", friends);
        sendMessage(session, objectMapper.writeValueAsString(response));
    }
    // 处理获取历史消息
    private void handleGetHistoricalMessages(Map<String, Object> data, Session session) throws IOException {
        String sendMessage = (String) data.get("sendmessage");
        String receiveMessage = (String) data.get("receivemessage");
        List<Message> messages = MessageService.getHistoricalMessages(sendMessage, receiveMessage);
        Map<String, Object> response = new HashMap<>();
        response.put("type", 2); // 返回请求ID
        response.put("messages",messages);
        sendMessage(session, objectMapper.writeValueAsString(response));
    }
    // 处理发送消息
    private void handleSendMessage(Map<String, Object> data) {
        String sendMessage = (String) data.get("sendmessage");
        String receiveMessage = (String) data.get("receivemessage");
        String content = (String) data.get("content");
        int type=5;

        boolean saveMessageSuccess = MessageService.sendMessage(sendMessage,content,receiveMessage,type);
        if (saveMessageSuccess) {
            broadcastMessage(data);
        }
    }
    // 发送消息
    private void sendMessage(Session session, String message) throws IOException {
        session.getBasicRemote().sendText(message);
    }
    //  广播消息
    private void broadcastMessage(Map<String, Object> message) {
        synchronized (sessions) {
            for (Session client : sessions) {
                try {
                    client.getBasicRemote().sendText(objectMapper.writeValueAsString(message));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

